import { Module } from 'vuex'
import { updateWorkOrderStatus, getWorkOrder, palletCodeSku } from '@/api/modules/in-work'
import deepClone from '@/utils/deep-clone'

interface State {
  form: formInfo //基本数据
  info: any //系统入库单数据
  scanInOrderDetailId: any //存储扫描过的单据
}

interface formInfo {
  inOrderCode: string
  theme: string
  operName: string
  auditName: string
  sourceType: string
  tenantId: string
  summary: string
}

const store: Module<State, unknown> = {
  namespaced: true,
  state() {
    return {
      form: {
        inOrderCode: '',
        theme: '',
        operName: '',
        auditName: '',
        sourceType: '',
        tenantId: '',
        summary: '',
      },
      info: {
        imsStockInOrderDetailList: [],
      },
      scanInOrderDetailId: [],
    }
  },
  getters: {
    getFormInfo(state) {
      return state.form
    },
  },
  mutations: {
    setFromInfo(state, value) {
      state.form = value
    },
    setInfo(state, value) {
      state.info = value
    },
    setClearScanInOrderDetailId(state) {
      state.scanInOrderDetailId = []
    },
    setScanInOrderDetailId(state, value) {
      state.scanInOrderDetailId.push(value)
    },
  },
  actions: {
    async setUpdateWorkOrderStatusAction({ state, commit }, list) {
      const info = deepClone(state.info)
      const arr = list || info.imsStockInOrderDetailList
      arr.map((modal: any) => {
        if (modal.status !== 1) {
          modal.status = modal.palletCodeSkuList.length === +modal.packageQuantity ? 1 : 0
        }

        // modal.palletCodeSkuList = modal.palletCodeSkuList.filter((item) => typeof item !== 'string')
      })
      const bool = info.imsStockInOrderDetailList.every((item) => item.status === 1)
      if (bool) {
        info.pickStatus = 2
      } else {
        info.pickStatus = 1
      }

      info.imsStockInOrderDetailList.map((item) => {
        delete item['palletCodeSkuList']
        return item
      })

      await updateWorkOrderStatus(info)
      // 更新数据
      const { data } = await getWorkOrder(info.inOrderId)
      commit('setInfo', data)
    },
    // 添加产品码绑定托盘码
    async setPalletCodeSkuAction({ state }, value) {
      const info = state.info
      const params = {
        ...info,
        ...value,
        status: 0,
        inOrderId: Number(info.inOrderId),
      }
      await palletCodeSku(params)
    },
  },
  modules: {},
}

export default store
